"""
Math exercises
"""
import random

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW, CENTER
from toga.validators import MatchRegex


class tongpaiapp(toga.App):
    def startup(self):
        main_box = toga.Box(style=Pack(direction=COLUMN, padding_top=50, alignment=CENTER))
        self.exercises_total_count_input = toga.TextInput(
            placeholder='单次练习的题目数量(默认20)',
            style=Pack(width=315, padding=5)
        )
        # 数值范围输入框需要验证用户输入格式是否正确
        self.exercises_first_number_input = toga.TextInput(
            placeholder='第一个数：最小值-最大值(默认1-20)',
            style=Pack(width=315, padding=5),
            validators=[MatchRegex(r'^\d+-\d+$', error_message='正确格式：最小值-最大值（例如：1-10）')]
        )

        self.exercises_second_number_input = toga.TextInput(
            placeholder='第二个数：最小值-最大值(默认1-20)',
            style=Pack(width=315, padding=5),
            validators=[MatchRegex(r'^\d+-\d+$', error_message='正确格式：最小值-最大值（例如：1-10）')]
        )

        self.exercises_sybol_list_input = toga.TextInput(
            placeholder='运算符号：+,-,*,/,%(默认+,-)',
            style=Pack(width=315, padding=5),
            validators=[MatchRegex(r'^[\+\-\*\/\%,，]$', error_message='正确格式：最小值-最大值（例如（+，-，*，/，%））')]
        )

        # 大的 开始练习 按钮 居中
        self.start_button = toga.Button(
            '开始练习',
            on_press=self.start_exercise,
            style=Pack(padding=5, width=315, font_size=40, background_color='red')
        )

        main_box.add(self.exercises_total_count_input)
        main_box.add(self.exercises_first_number_input)
        main_box.add(self.exercises_second_number_input)
        main_box.add(self.exercises_sybol_list_input)
        main_box.add(self.start_button)

        self.main_window = toga.MainWindow(title='童派练习题APP')
        self.main_window.content = main_box
        self.main_window.show()


    def init_db(self):
        self.exercises_count = 1
        self.exercises_total_count = int(self.exercises_total_count_input.value)
        self.exercises_first_number_min = int(str(self.exercises_first_number_input.value).split('-')[0])
        self.exercises_first_number_max = int(str(self.exercises_first_number_input.value).split('-')[1])
        self.exercises_second_number_min = int(str(self.exercises_second_number_input.value).split('-')[0])
        self.exercises_second_number_max = int(str(self.exercises_second_number_input.value).split('-')[1])
        self.exercises_sybol_list = str(self.exercises_sybol_list_input.value).replace('，', ',').split(',')
        self.exercises_result_list = list()  # [[题号, 题目内容, 提交答案, 参考答案, 成绩分数], ...]

    def start_exercise(self, button):
        if self.exercises_total_count_input.value == '':
            self.exercises_total_count_input.value = 20
        if self.exercises_first_number_input.value == '':
            self.exercises_first_number_input.value = '1-20'
        if self.exercises_second_number_input.value == '':
            self.exercises_second_number_input.value = '1-20'
        if self.exercises_sybol_list_input.value == '':
            self.exercises_sybol_list_input.value = '+,-'
        self.init_db()
        # 跳转练习题页面
        self.ExercisePage()

    async def submit_answer(self, button):
        if self.exercises_answer_input.value == '':
            await self.main_window.dialog(
                toga.ErrorDialog('错误提示', '请输入您的答案')
            )
            return
        self.exercises_result_list.append([self.exercises_count,
                                           self.exercises_title.text,
                                           int(self.exercises_answer_input.value),
                                           eval(self.exercises_title.text.split('=')[0]),
                                           1 if self.exercises_answer_input.value is None or
                                               int(self.exercises_answer_input.value) == \
                                               eval(self.exercises_title.text.split('=')[0]) else 0]
                                          )
        if self.exercises_count >= self.exercises_total_count:
            score = sum(map(lambda x: x[4], self.exercises_result_list))
            self.exercises_error_list = list(filter(lambda x: x[4] == 0, self.exercises_result_list))
            self.exercises_error_content = ''
            for i in self.exercises_error_list:
                self.exercises_error_content += f'第{i[0]}题：{i[1]}，提交答案：{i[2]}，参考答案：{i[3]}\n'
            self.init_db()
            await self.main_window.dialog(
                toga.InfoDialog('提示', f'练习结束!\n您的成绩为：{score}\n错题汇总：\n{self.exercises_error_content}')
            )
        else:
            self.exercises_count += 1
        self.ExercisePage()

    async def skip_answer(self, button):
        self.exercises_result_list.append([self.exercises_count, self.exercises_title.text, None,
                                           eval(self.exercises_title.text.split('=')[0]), 0]
                                          )
        if self.exercises_count >= self.exercises_total_count:
            score = sum(map(lambda x: x[4], self.exercises_result_list))
            self.exercises_error_list = list(filter(lambda x: x[4] == 0, self.exercises_result_list))
            self.exercises_error_content = ''
            for i in self.exercises_error_list:
                self.exercises_error_content += f'第{i[0]}题：{i[1]}，提交答案：{i[2]}，参考答案：{i[3]}\n'
            self.init_db()
            await self.main_window.dialog(
                toga.InfoDialog('提示', f'练习结束!\n您的成绩为：{score}\n错题汇总：\n{self.exercises_error_content}')
            )
        else:
            self.exercises_count += 1
        self.ExercisePage()

    async def show_answer(self, button):
        await self.main_window.dialog(
            toga.InfoDialog('提示', f'参考答案：{eval(self.exercises_title.text.split('=')[0])}')
        )
        return

    def ExercisePage(self):
        '''
        1、练习题内容
        2、答案输入框
        3、提交按钮
        4、跳过按钮
        5、查看答案
        6、点击提交按钮后弹出答案提示框
        :return:
        '''
        main_box = toga.Box(style=Pack(direction=COLUMN, padding_top=50, padding_bottom=50, alignment=CENTER))
        first_number = random.randint(self.exercises_first_number_min, self.exercises_first_number_max)
        second_number = random.randint(self.exercises_second_number_min, self.exercises_second_number_max)
        symbol = random.choice(self.exercises_sybol_list)
        self.exercises_title_box = toga.Box(style=Pack(direction=ROW, padding=10, alignment=CENTER))
        self.exercises_title_index = toga.Label(f'第{self.exercises_count}/{self.exercises_total_count}题:',
                                                style=Pack(background_color='red',
                                                           padding=10,
                                                           font_size=40))
        self.exercises_title = toga.Label(f'{first_number}{symbol}{second_number}=?',
                                          style=Pack(background_color='red',
                                                     padding=10,
                                                     font_size=40))
        self.exercises_title_box.add(self.exercises_title_index)
        self.exercises_title_box.add(self.exercises_title)
        self.exercises_answer_input = toga.TextInput(placeholder='请输入您的答案', style=Pack(width=315, padding=10))
        exercises_button_box = toga.Box(
            style=Pack(direction=ROW, padding=10),
            children=[
                toga.Button('提交答案',
                            style=Pack(width=100, padding=5, color='green'),
                            on_press=self.submit_answer),
                toga.Button('跳过本题',
                            style=Pack(width=100, padding=5, color='green'),
                            on_press=self.skip_answer),
                toga.Button('查看答案',
                            style=Pack(width=100, padding=5, color='blue'),
                            on_press=self.show_answer),
            ]
        )

        main_box.add(self.exercises_title_box)
        main_box.add(self.exercises_answer_input)
        main_box.add(exercises_button_box)

        self.main_window.content = main_box
        self.main_window.show()

def main():
    return tongpaiapp()
